//
//  ExamineViewController.m
//  gdemm
//
//  Created by 乔明超 on 16/10/30.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "ExamineViewController.h"
#import "NavigationController.h"
#import "SliderController.h"
#import "ExamineManager.h"
#import "ExamineActionListener.h"
#import "EvaluationHeaderView.h"
#import "WIFIManager.h"
#import "ExamineTitleView.h"
#import "ExamineTableViewCell.h"
#import "UserDefaultsUtil.h"
#import "TimeUtil.h"
#import "ApiSupport.h"
#import "KeyChain.h"
#import "HttpUtil.h"
@interface ExamineViewController ()<ExamineActionListener>
@property(nonatomic,strong)EvaluationHeaderView * headerView;
@property(strong,nonatomic)NSMutableArray *exmaineItems;
@property(strong,nonatomic)NSMutableArray *rootCheckItems;
@property(strong,nonatomic)NSMutableArray *mobileConfigCheckItems;
@property(strong,nonatomic)NSMutableArray *WlanCheckItems;
@property(strong,nonatomic)NSMutableArray *PackageCheckItems;
@property(nonatomic,strong) NavigationController *navC;
@property(strong,nonatomic)UITableView *tableView;
@property(assign,nonatomic)BOOL isFinished;
@property(assign,nonatomic)BOOL isSafe;
@property(assign,nonatomic)BOOL isRoot;
@end

@implementation ExamineViewController
static NSString *reuseId = @"exmine";


- (NSMutableArray *)exmaineItems{
    if (_exmaineItems == nil) {
        _exmaineItems = [NSMutableArray array];
    }
    
    return _exmaineItems;
}

- (NSMutableArray *)rootCheckItems{
    if (_rootCheckItems == nil) {
        _rootCheckItems = [NSMutableArray array];
    }
    
    return _rootCheckItems;
}

- (NSMutableArray *)mobileConfigCheckItems{
    if (_mobileConfigCheckItems == nil) {
        _mobileConfigCheckItems = [NSMutableArray array];
    }
    return _mobileConfigCheckItems;
}

- (NSMutableArray *)WlanCheckItems{
    if (_WlanCheckItems == nil) {
        _WlanCheckItems = [NSMutableArray array];
    }
    
    return _WlanCheckItems;
}
- (NSMutableArray *)PackageCheckItems{
    if (_PackageCheckItems == nil) {
        _PackageCheckItems = [NSMutableArray array];
    }
    
    return _PackageCheckItems;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(skinSwitchHandler) name:@"skinswitch" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(evaluationComplicate) name:progrossViewNotification object:nil];
    self.view.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
   
    [self setupNavBarStyle];
    [self setupView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [ExamineManager getInstance].mActListener = self;
    [[ExamineManager getInstance] startExamine];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
    self.navC.cover.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
}

- (void)setupNavBarStyle{
    
    self.navigationItem.title = nil;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [Utils colorWithKey:@"mainBgColor"];
    self.navC = (NavigationController *)self.navigationController;
    self.navC.cover.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[Utils getImageByDevce:@"navigationBar_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemHnadler)];
    
}
- (void)setupView{
    if ([DeviceTypeJudge isPadDeviceType]) {
        [self setupIpadView];
    }else{
    
        [self setupIphoneView];
    }

}

- (void)setupIpadView{

    self.headerView = [[EvaluationHeaderView alloc]init];
    self.headerView.frame = CGRectMake(0, 0, WINDOWWIDTH, 400);
    [self.headerView onClickBtnBlock:^{
        [ExamineManager getInstance].mActListener = self;
        [[ExamineManager getInstance] startExamine];
    }];
    [self.view addSubview:self.headerView];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), WINDOWWIDTH, WINDOWHEIGHT - CGRectGetMaxY(self.headerView.frame)) style:UITableViewStyleGrouped];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 120, 0);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = 30;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //self.tableView.allowsSelection = NO;
    [self.view addSubview:self.tableView];
}
- (void)setupIphoneView{
    self.headerView = [[EvaluationHeaderView alloc]init];
    self.headerView.frame = CGRectMake(0, 0, WINDOWWIDTH, 210*KHeightScale);
    [self.headerView onClickBtnBlock:^{
        [ExamineManager getInstance].mActListener = self;
        [[ExamineManager getInstance] startExamine];
    }];
    [self.view addSubview:self.headerView];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), WINDOWWIDTH, WINDOWHEIGHT - CGRectGetMaxY(self.headerView.frame)) style:UITableViewStyleGrouped];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 120, 0);
    //self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight ;//| UIViewAutoresizingFlexibleWidth;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = 26;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
}

/**
 *  肤色切换
 */

- (void)skinSwitchHandler{
    self.tabBarItem.selectedImage = [[Utils imageWithKey:@"tabBar_evaluation_click_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.view.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.navigationController.navigationBar.barTintColor = [Utils colorWithKey:@"mainBgColor"];
    self.navC.cover.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
}

//侧滑栏滑动
- (void)leftBarButtonItemHnadler{
    [[SliderController sharedInstance]leftTapHandler];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


#pragma mark - ExamineItem协议实现

//评测开始
- (void)onExamineStart{
    [self.exmaineItems removeAllObjects];
    [self.PackageCheckItems removeAllObjects];
    self.isSafe = NO;
    self.isRoot = NO;
    self.isFinished = NO;
    [self.headerView startTest];
    [self.tableView reloadData];
}

- (void)onExamineItemChange:(NSString *)newExamineItem{
    
    [self.exmaineItems addObject:newExamineItem];
    [self.tableView reloadData];
}

//每个测评项的测评信息及结果
- (void)onExamineInfo:(NSString *)newExamineContent{
   
    NSArray *result = [newExamineContent componentsSeparatedByString:@"&"];
    HRLog(@"the content is %@ -------%@",newExamineContent,result[0]);
    if (result.count > 2) {
        if ([result[0] isEqualToString:@"RootCheck"]) {
            ItemModel *info = [[ItemModel alloc]init];
            info.itemInfo = result[1];
            info.state = [result[2] boolValue];
            [self.rootCheckItems removeAllObjects];
            [self.rootCheckItems addObject:info];
            
        }else if ([result[0] isEqualToString:@"WlanCheck"]){
            
            ItemModel *info = [[ItemModel alloc]init];
            info.itemInfo = result[1];
            info.state = [result[2] boolValue];
            [self.WlanCheckItems removeAllObjects];
            [self.WlanCheckItems addObject:info];
        
        }else if ([result[0] isEqualToString:@"PackageCheck"]){
            NSString *str = result[1];
            if (str.length != 0) {
            
                ItemModel *info = [[ItemModel alloc]init];
                info.itemInfo = result[1];
                info.state = [result[2] boolValue];
                [self.PackageCheckItems addObject:info];
            }
        
        }else if ([result[0] isEqualToString:@"MobileConfigCheck"]){
            ItemModel *info = [[ItemModel alloc]init];
            info.itemInfo = result[1];
            info.state = [result[2] boolValue];
            [self.mobileConfigCheckItems removeAllObjects];
            [self.mobileConfigCheckItems addObject:info];
        }
    }

    [self.tableView reloadData];
}

//测评完成
- (void)onExamineFinish:(BOOL)result{
    NSDictionary *dict = [ExamineManager getInstance].examineResult;
    if (dict[EXAMINE_ROOT_STATUS_TAG] != nil) {
        BOOL isRoot = [dict[EXAMINE_ROOT_STATUS_TAG] boolValue];
        self.isRoot = !isRoot;
    }
    [NSThread sleepForTimeInterval:0.2];
    self.isSafe = result;
    self.isFinished = YES;
}

//更新UI
- (void)onExamineUpdateUI{

    [self.exmaineItems removeAllObjects];
    [self.rootCheckItems removeAllObjects];
    [self.mobileConfigCheckItems removeAllObjects];
    [self.WlanCheckItems removeAllObjects];
    [self.PackageCheckItems removeAllObjects];
    self.headerView.evaluationState = EvaluationResultQualified;
    [self.tableView reloadData];
}

#pragma mark - UITableDelegate,UITableDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return [self.exmaineItems count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self.exmaineItems[section] isEqualToString:EXAMINE_ROOT_STATUS_TAG]) {
        return [self.rootCheckItems count];
    }else if ([self.exmaineItems[section] isEqualToString:EXAMINE_WLAN_STATUS_TAG]){
    
        return [self.WlanCheckItems count];
    }else if ([self.exmaineItems[section] isEqualToString:EXAMINE_PACKAGE_STATUS_TAG]){
    
        return [self.PackageCheckItems count];
    }else if ([self.exmaineItems[section] isEqualToString:EXAMINE_CONFIG_STATUS_TAG]){
        
        return [self.mobileConfigCheckItems count];
    }else{
        return 0;
    }
   
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ExamineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[ExamineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId];
        cell.backgroundColor = [UIColor clearColor];
    }
    if ([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_ROOT_STATUS_TAG]) {
        cell.item = self.rootCheckItems[indexPath.row];
        
    }else if ([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_CONFIG_STATUS_TAG]){
        cell.item = self.mobileConfigCheckItems[indexPath.row];
        
    }else if ([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_WLAN_STATUS_TAG]){
        cell.item = self.WlanCheckItems[indexPath.row];
        
    }else if ([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_PACKAGE_STATUS_TAG]){
        cell.item = self.PackageCheckItems[indexPath.row];
    
    }
    if (!self.isFinished) {
        [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSInteger height ;
    if ([DeviceTypeJudge isPadDeviceType]) {
        height = 64;
    }else{
        height = 32;
    }
    ExamineTitleView *  headerView = [[ExamineTitleView alloc]initWithFrame:CGRectMake(0, 0, WINDOWWIDTH, height)];
    headerView.title = self.exmaineItems[section];
    return headerView;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([DeviceTypeJudge isPadDeviceType]) {
        return  64;
    }else{
        return 42;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_CONFIG_STATUS_TAG]) {
        ItemModel *item = self.mobileConfigCheckItems[indexPath.row];
        if (!item.state) {
            NSString *uuidStr = [ApiSupport generateMobileConfigUrl];
            NSMutableDictionary *uuidDict = (NSMutableDictionary *)[KeyChain load:KEY_SERVICENAME];
            NSString *uuid = uuidDict[KEY_UUID];
            //设置参数
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"uuid"] = uuid;
            NSData *data = [HttpUtil httpRequestSyncWithUrl:uuidStr andParams:params];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([dict[@"status"] isEqualToString:@"success"]) {
                NSString *mobilePath = [ApiSupport installMobileConfigUrl];
                HRLog(@"mobile ==== %@",mobilePath);
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:mobilePath]];
            }else{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.view makeToast:NSLocalizedString(@"str_genMobileConfigFailed", @"描述文件生成失败,请退出重新登录")];
                });
            }
        }
    }else if([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_WLAN_STATUS_TAG]){
        ItemModel *item = self.WlanCheckItems[indexPath.row];
        if (!item.state) {
            [self.view makeToast:@"请手动断开WIFI连接,连接其他WIFI,再重新测评"];
        }
    }else if([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_PACKAGE_STATUS_TAG]){
        ItemModel *item = self.PackageCheckItems[indexPath.row];
        if (!item.state) {
            [self.view makeToast:@"请手动卸载违规应用,重新测评"];
        }
        
    }else if([self.exmaineItems[indexPath.section] isEqualToString:EXAMINE_ROOT_STATUS_TAG]){
        ItemModel *item = self.rootCheckItems[indexPath.row];
        if (!item.state) {
            [self.view makeToast:@"系统已越狱,请手动修复"];
        }
    }
}

#pragma mark - 评测通知
-(void)evaluationComplicate{
    
    while (self.isFinished == NO ) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
    
    HRLog(@"safe = %d root = %d",_isSafe,_isRoot);
    if (self.isSafe) {
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_LASTEXAMINETIME :[TimeUtil currentTime]];
        [[UserDefaultsUtil shareInstance]saveIntConfig:LC_LASTEXAMINERESULT :1];
        self.headerView.evaluationState = EvaluationResultQualified;
    }else if (self.isRoot){
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_LASTEXAMINETIME :[TimeUtil currentTime]];
        [[UserDefaultsUtil shareInstance]saveIntConfig:LC_LASTEXAMINERESULT :2];
        //self.headerView.evaluationState = EvaluationResultQualified;
        self.headerView.evaluationState = EvaluationResultHigtRisk;
    }else{
        [[UserDefaultsUtil shareInstance]saveStringConfig:LC_LASTEXAMINETIME :[TimeUtil currentTime]];
        [[UserDefaultsUtil shareInstance]saveIntConfig:LC_LASTEXAMINERESULT :2];
        //self.headerView.evaluationState = EvaluationResultQualified;
        self.headerView.evaluationState = EvaluationResultUnualified;
    }
    
}

#pragma mark - 修复危险项
- (void)onKeyRepair{
    
}
@end
